package com.it.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String,Date> {
    @Override
    public Date convert(String source) {
        Date date=null;
        if(source==null){
            throw new RuntimeException("日期有误！");
        }
        if(source.matches("\\d{4}-\\d{2}-\\d{2}")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            try {
                date=sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期有误！");
            }
        }
        else if(source.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            try {
                date= sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期有误！");
            }
        }
        else if(source.matches("\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            try {
                date= sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期有误！");
            }
        }
        else if(source.matches("\\d{4}/\\d{2}/\\d{2}")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
            try {
                date= sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期有误！");
            }
        }
        return date;
    }

}
